<template>
  <!-- 加载器 -->
  <Loading v-if="isLoading"></Loading>
  <div
    class="w-1/3 mx-auto mt-40 shadow-2xl shadow-blue-300 rounded-box"
    v-if="!isLoading"
  >
    <!-- avatar -->
    <div class="avatar flex justify-center">
      <div class="w-24 rounded-full mt-4">
        <label for="avatar-input" class="cursor-pointer">
          <img :src="currentAvatar" />
        </label>
      </div>
    </div>
    <input
      id="avatar-input"
      type="file"
      accept="image/*"
      @change="handleAvatarChange"
      class="hidden"
    />
    <div class="mx-auto">
      <!-- name -->
      <label class="input input-bordered flex gap-2 my-4 w-3/4 mx-auto">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 16 16"
          fill="currentColor"
          class="h-4 w-4 opacity-70"
        >
          <path
            d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM12.735 14c.618 0 1.093-.561.872-1.139a6.002 6.002 0 0 0-11.215 0c-.22.578.254 1.139.872 1.139h9.47Z"
          />
        </svg>
        <input type="text" class="grow" v-model="name" disabled />
      </label>

      <ul class="menu bg-base-200 rounded-box w-3/4 mx-auto" v-if="!isStudent">
        <li>
          <details open>
            <summary>Class In Charge</summary>
            <ul>
              <li v-for="(item, index) in classInCharge" :key="index">
                <a class="pointer-events-none"
                  >Class {{ item.split("|")[0] }} | Grade
                  {{ item.split("|")[1] }}</a
                >
              </li>
            </ul>
          </details>
        </li>
      </ul>
    </div>
    <!-- button -->
    <div class="text-center">
      <button class="btn btn-primary mx-2 my-2" @click="onClick">
        Update Avatar
      </button>
    </div>
  </div>
</template>
<script setup>
import { uploadAvatar } from "@/services/apiStorage";
import { ref, onMounted } from "vue";
import { useUserStore } from "@/stores/user";
import { storeToRefs } from "pinia";
import { getTeacherByTeacherId } from "@/services/apiTeacher";
import { getConfig } from "@/ultils/configHelper";
import { useToast } from "vue-toastification";
import Loading from "@/ui/Loading.vue";
import { getToken } from "@/ultils/tokenHelper";
import { updateStudent } from "@/services/ApiStudent";

const isLoading = ref(true);

const userStore = useUserStore();
const toast = useToast();
const { user, isStudent } = storeToRefs(userStore);
const { updateUser } = userStore;

const currentAvatar = ref(user.value.avatar);
const newAvatarFile = ref(null);

const name = ref(null);
const classInCharge = ref([]);

onMounted(async () => {
  isLoading.value = true;
  currentAvatar.value = user.value.avatar;
  console.log(user.value.avatar);
  name.value = user.value.display_name;
  // 直接读取pinia中数据会报错，因为pinia中数据是异步的,一开始只有avatar
  // const classes = await getTeacherByTeacherId(user.value.sub);
  //改进从localstorage中获取用户名
  if (!isStudent.value) {
    const teacherData = getToken();
    // console.log(teacherData.user.id);
    const classes = await getTeacherByTeacherId(teacherData.user.id);
    classInCharge.value = JSON.parse(classes[0].class_in_charge);
    console.log(classInCharge.value);
  }
  isLoading.value = false;
});

function handleAvatarChange(e) {
  const file = e.target.files[0];
  newAvatarFile.value = file;
  const avatarURL = URL.createObjectURL(file);
  currentAvatar.value = avatarURL;
}

async function onClick() {
  if (!newAvatarFile.value) {
    toast.warning("Please select an avatar file");
    return;
  }

  toast.info("Uploading...");

  const supabaseURL = getConfig("SUPABASE_URL");

  // const tokenName = getConfig("SUPABASE_AUTH_TOKEN");
  // const userData = JSON.parse(localStorage.getItem(tokenName));
  const userData = getToken();
  const AvatarName = `${userData.user.email}-${Date.now()}`;
  await uploadAvatar(newAvatarFile.value, AvatarName);

  const newAvatar = `${supabaseURL}/storage/v1/object/public/avatar/public/${AvatarName}`;

  if (isStudent.value) {
    const data = updateStudent(user.value.sub, { avatar: newAvatar });
    console.log(data);
  }

  // 手动更新LocalStorage
  userData.user.user_metadata.avatar = newAvatar;
  localStorage.setItem(
    getConfig("SUPABASE_AUTH_TOKEN"),
    JSON.stringify(userData)
  );

  const updateData = { avatar: newAvatar };
  //添加上isStudent字段
  if (isStudent.value) {
    updateData.isStudent = true;
  }
  //update user avatar
  updateUser(updateData);
  toast.success("Avatar updated successfully");
  // console.log(updateData);
}
</script>
